﻿using System;
using System.Diagnostics.Contracts;
using System.IO;
using OpenLS.Spreadsheet.Formats.Biff.Cryptography;

namespace OpenLS.Spreadsheet.Formats.Biff.OfficeArt
{
    class MD4Digest
    {
        private readonly byte[] _data;
        public MD4Digest(BinaryReader reader): this(reader.ReadBytes(16))
        {
        }
        public MD4Digest(byte [] data)
        {
            Contract.Requires(data != null);
            Contract.Requires(data.Length == 16);
            _data = data;
        }
        public void Write (BinaryWriter writer)
        {
            Contract.Assert(_data != null);
            Contract.Assert(_data.Length == 16);
            writer.Write(_data);
        }

        public static MD4Digest Compute(byte[] data)
        {
            Contract.Requires(data != null);
            var m = new MD4CryptoServiceProvider();
            return new MD4Digest(m.ComputeHash(data));
        }

#if DEBUG
        public void Verify(byte[] blipFileData)
        {
            var m = new MD4CryptoServiceProvider();
            byte [] test = new byte[4];
            int i = 0;
            foreach (var c in "test")
            {
                test[i++] = (byte) c;
            }
            byte[] answer = m.ComputeHash(test);

            byte[] newHash = m.ComputeHash(blipFileData);
            Contract.Assert(newHash.Length == 16);
            ;
            for ( i = 0; i < 16; i++ )
                Contract.Assert(newHash[i] == this._data[i]);
        }
#endif
    }
}